package com.ktjiaoyu.ktmall.servlet.api;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.ktmall.entity.User;
import com.ktjiaoyu.ktmall.service.UserService;
import com.ktjiaoyu.ktmall.service.impl.UserServiceImpl;
import com.ktjiaoyu.ktmall.utils.R;
import com.ktjiaoyu.ktmall.utils.RedisUtil;
import com.ktjiaoyu.ktmall.utils.RequestUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.UUID;

@WebServlet(name="UserServlet",urlPatterns = "/api/user")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        R result = null;
        String body = RequestUtil.readBody(request);
        JSONObject params = JSONObject.parseObject(body);
        String opr = request.getParameter("opr");
        if (opr == null) {
            opr ="";
        }
        switch (opr) {
            case "login":
                result = doLogin(request,params);
                break;
            default:
                result = R.fail().msg("未知操作");
        }
        out.print(result!=null? JSON.toJSONString(result):"{}");
        out.flush();
        out.close();
    }
    private R doLogin(HttpServletRequest request,JSONObject params) {
        String username = params.getString("username");
        String password = params.getString("password");
        if (username == null||password == null) {
            return R.fail().msg("用户名或密码错误");
        }
        User user = userService.login(username, password);
        if (user != null) {
            user.setLastLoginTime(new Date());
//            userService.update(user);
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            RedisUtil.set("TOKEN:"+token,String.valueOf(user.getId()),1800);
            return R.ok().data(new JSONObject().fluentPut("token","Bearer "+token));
        }else {
            return R.fail().msg("用户名或密码错误");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        R result = null;
        String opr = request.getParameter("opr");
        if (opr == null) {
            opr ="";
        }
        switch (opr) {
            case "info":
                result = doGetUserInfo(request);
                break;
            default:
                result= R.fail().msg("未知操作");
        }
        out.print(result!=null? JSON.toJSONString(result):"{}");
        out.flush();
        out.close();
    }
    private R doGetUserInfo(HttpServletRequest request) {
        String userId = RedisUtil.getUserIdFromToken(request);
        User user = userService.findById(userId);
        if (user != null) {
            user.setPassword(null);
            JSONObject userInfo = new JSONObject()
                    .fluentPut("id",user.getId())
                    .fluentPut("username",user.getUsername())
                    .fluentPut("nickname",user.getNickname())
                    .fluentPut("avatar",user.getAvatar())
                    .fluentPut("phone",user.getPhone())
                    .fluentPut("email",user.getEmail());
            return R.ok().data(userInfo);
        }else {
            return R.fail().msg("获取用户信息失败");
        }
    }
}
